package com.rico.common.exception;

import com.rico.common.enums.HttpStatus;
import com.rico.common.response.MessageUtils;
import com.rico.common.response.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.io.IOException;

/**
 * @author 吴泽胜
 * @FileName ExceptionHandler
 * @date 2021-04-23 12:33 下午
 * @Software: IntelliJ IDEA
 */

// 不指定包默认加了@Controller和@RestController都能控制
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 空指针异常
     * @param ex
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public RestResponse nullPointerException(NullPointerException ex) {
        log.error(ex.getMessage(), ex);
        return MessageUtils.fail("空指针异常！");
    }

    /**
     * 文件上传异常
     * @param ex
     * @return
     */
    @ExceptionHandler(IOException.class)
    @ResponseBody
    public RestResponse ioException(IOException ex) {
        log.error(ex.getMessage(), ex);
        return MessageUtils.fail("文件上传异常！");
    }

    /**
     * 异常统一处理(最后的异常处理)
     */
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public RestResponse allException(Exception e) {
        log.info(e.getMessage());
        return MessageUtils.fail(HttpStatus.NoOK.getMessage());
    }
}
